// 存储用户数据的本地存储
let users = JSON.parse(localStorage.getItem('registeredUsers')) || [];

// 表单切换功能
const loginTab = document.getElementById('login-tab');
const registerTab = document.getElementById('register-tab');
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const formTitle = document.getElementById('form-title');
const formSubtitle = document.getElementById('form-subtitle');
const toggleText = document.getElementById('toggle-text');
const toggleButton = document.getElementById('toggle-button');

// 清除所有错误提示
function clearErrors() {
    document.querySelectorAll('.error-message').forEach(el => {
        el.textContent = '';
    });
    document.querySelectorAll('input').forEach(el => {
        el.classList.remove('form-error');
    });
}

// 显示错误信息
function showError(elementId, message) {
    const errorElement = document.getElementById(elementId);
    const inputElement = document.getElementById(elementId.replace('-error', ''));
    
    errorElement.textContent = message;
    inputElement.classList.add('form-error');
}

// 切换到登录表单
function showLoginForm() {
    clearErrors();
    loginForm.classList.remove('hidden');
    registerForm.classList.add('hidden');
    loginTab.classList.add('bg-primary', 'text-white');
    loginTab.classList.remove('text-gray-600');
    registerTab.classList.remove('bg-primary', 'text-white');
    registerTab.classList.add('text-gray-600');
    formTitle.textContent = '登录';
    formSubtitle.textContent = '请输入您的账号信息登录';
    toggleText.textContent = '还没有账号?';
    toggleButton.textContent = '立即注册';
}

// 切换到注册表单
function showRegisterForm() {
    clearErrors();
    registerForm.classList.remove('hidden');
    loginForm.classList.add('hidden');
    registerTab.classList.add('bg-primary', 'text-white');
    registerTab.classList.remove('text-gray-600');
    loginTab.classList.remove('bg-primary', 'text-white');
    loginTab.classList.add('text-gray-600');
    formTitle.textContent = '注册';
    formSubtitle.textContent = '创建新账号，开始您的旅程';
    toggleText.textContent = '已有账号?';
    toggleButton.textContent = '立即登录';
}

// 绑定切换事件
loginTab.addEventListener('click', showLoginForm);
registerTab.addEventListener('click', showRegisterForm);
toggleButton.addEventListener('click', () => {
    if (loginForm.classList.contains('hidden')) {
        showLoginForm();
    } else {
        showRegisterForm();
    }
});

// 密码显示/隐藏功能
document.querySelectorAll('.toggle-password').forEach(button => {
    button.addEventListener('click', function() {
        const targetId = this.getAttribute('data-target');
        const passwordInput = document.getElementById(targetId);
        const icon = this.querySelector('i');
        
        // 切换密码可见性
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });
});

// 登录表单提交处理
loginForm.addEventListener('submit', function(e) {
    e.preventDefault();
    clearErrors();
    
    const email = document.getElementById('login-email').value;
    const password = document.getElementById('login-password').value;
    let isValid = true;
    
    // 简单验证
    if (!email) {
        showError('login-email-error', '请输入邮箱');
        isValid = false;
    }
    
    if (!password) {
        showError('login-password-error', '请输入密码');
        isValid = false;
    }
    
    if (!isValid) return;
    
    // 查找用户
    const user = users.find(u => u.email === email);
    
    if (!user) {
        // 用户不存在
        showError('login-email-error', '该用户不存在，请先注册');
        return;
    }
    
    // 验证密码
    if (user.password !== password) {
        showError('login-password-error', '密码不正确');
        return;
    }
    
    // 登录成功，跳转到主页面
    localStorage.setItem('currentLoginEmail', email);
    alert('登录成功，即将跳转到主页面');
    window.location.href = 'dashboard.html';
});

// 注册表单提交处理
registerForm.addEventListener('submit', function(e) {
    e.preventDefault();
    clearErrors();
    
    const name = document.getElementById('register-name').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm').value;
    let isValid = true;
    
    // 验证
    if (!name) {
        showError('register-name-error', '请输入用户名');
        isValid = false;
    }
    
    if (!email) {
        showError('register-email-error', '请输入邮箱');
        isValid = false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        showError('register-email-error', '请输入有效的邮箱地址');
        isValid = false;
    } else if (users.some(u => u.email === email)) {
        showError('register-email-error', '该邮箱已被注册');
        isValid = false;
    }
    
    if (!password) {
        showError('register-password-error', '请设置密码');
        isValid = false;
    } else if (password.length < 8) {
        showError('register-password-error', '密码长度不能少于8位');
        isValid = false;
    }
    
    if (!confirmPassword) {
        showError('register-confirm-error', '请再次输入密码');
        isValid = false;
    } else if (password !== confirmPassword) {
        showError('register-confirm-error', '两次输入的密码不一致');
        isValid = false;
    }
    
    if (!isValid) return;
    
    // 注册成功，保存用户信息
    users.push({
        name: name,
        email: email,
        password: password,
        registeredAt: new Date().toISOString()
    });
    
    // 保存到本地存储
    localStorage.setItem('registeredUsers', JSON.stringify(users));
    
    // 显示成功消息并切换到登录表单
    alert('注册成功，请登录');
    showLoginForm();
    
    // 自动填充邮箱
    document.getElementById('login-email').value = email;
});

const userMenuButton = document.getElementById('user-menu-button');
const userDropdownMenu = document.getElementById('user-dropdown-menu');

// 点击头像切换下拉菜单显示状态
if (userMenuButton && userDropdownMenu) {
    userMenuButton.addEventListener('click', function() {
        userDropdownMenu.classList.toggle('hidden');
    });

    // 点击其他区域关闭下拉菜单
    document.addEventListener('click', function(event) {
        if (!userMenuButton.contains(event.target) && !userDropdownMenu.contains(event.target)) {
            userDropdownMenu.classList.add('hidden');
        }
    });

    // 退出登录功能
    const logoutBtn = document.getElementById('dropdown-logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentLoginEmail');
                window.location.href = 'index.html';
            }
        });
    }

    // 初始化用户信息到下拉菜单
    const loginEmail = localStorage.getItem('currentLoginEmail');
    const currentUser = users.find(user => user.email === loginEmail);
    
    if (currentUser) {
        const userNameEl = document.getElementById('dropdown-user-name');
        const userEmailEl = document.getElementById('dropdown-user-email');
        
        if (userNameEl) userNameEl.textContent = currentUser.name || '用户';
        if (userEmailEl) userEmailEl.textContent = currentUser.email || '';
    }
}
